const { User } = require('../models')


let index_g = async ctx => {
    if (ctx.session.username) {
        if (ctx.session.username === 'admin') return ctx.redirect('/')
        return ctx.render('user.html')
    }
    ctx.render('user.html')
}

let destroy_g = async ctx => {
    if (ctx.session.username) {
        ctx.session.username = ''
        ctx.session.id = 0
        ctx.body = { code: 200, msg: '退出成功' }
    }
    else {
        ctx.body = { err: 352, msg: '退出失败' }
    }
}



let loginVtr_p = async ctx => {
    let { username, password } = ctx.request.body;

    if (!username.trim() || !password.trim()) return ctx.body = { code: -120, msg: '没有输入必须信息' }

    let user = await User.findOne({ where: { user: username } })


    if (!user || user.getDataValue('pwd') !== password || user.getDataValue('isDeleted') === 1) return ctx.body = { code: -140, msg: '用户名或者密码错误' }

    if (user.getDataValue('isActived') === 0) return ctx.body = { code: -150, msg: '本账号存在违规行为，被暂停使用' }

    ctx.session.username = username
    ctx.session.id = user.getDataValue('id')

    ctx.body = {
        code: 200,
        id: user.getDataValue('roteId'),
        msg: '登录成功'
    }

}

let register_p = async ctx => {
    let { username, password, confimpwd } = ctx.request.body;

    if (!username.trim() || !password.trim() || password.trim() !== confimpwd.trim()) return ctx.body = { msg: '输入内容有误，请重试', code: 33 }

    let obj = await User.findOne({ where: { user: username } })

    if (obj) return ctx.body = { msg: '当前用户已经注册过了，无需再注册，请尝试登入', code: 45 }

    let user = await User.create({ user: username, pwd: password })


    if (user) {
        ctx.body = {
            code: 200,
            msg: '注册成功'
        }
    }
    else {
        ctx.body = {
            code: 46,
            msg: '注册失败'
        }
    }

}

//普通用户时通过分享链接跳转到登录界面，最后跳回到问卷调查界面,否则登录之后不做出反应
let springboard_g = async ctx => {
    let code = ctx.session.code

    console.log('验证code',code);

    if (code) {
        ctx.session.code = ''
        ctx.redirect(`/quest/writequest/${code}`)
    }
    else {
        ctx.redirect('/user')
    }
}



module.exports = {
    '/user': ['get', index_g],
    '/api/user/login': ['post', loginVtr_p],
    '/api/user/register': ['post', register_p],
    '/quest/springboard': ['get', springboard_g],
    '/user/destroy': ['get', destroy_g]
}


